import { BrowserWindow, ipcMain, dialog, shell, app } from 'electron'
import Winreg from 'winreg'
import { exec } from 'child_process'
import path from 'path'

export const bindWechatEvent = () => {

    // 读取注册表的示例
    const regKey = new Winreg({
        hive: Winreg.HKCU,
        key: '\\Software\\Tencent\\WeChat'
    })

    // 获取微信版本号
    ipcMain.handle('getWxVersion', async (event) => {
        return await new Promise((resolve, reject) => {
            // 获取注册表值
            regKey.get('Version', (err, item) => {
                if (err) {
                    reject(err);
                } else {
                    let hexVersion = item.value
                    // 去掉0x
                    hexVersion = hexVersion.slice(2)
                    // 把第一个字符（最高位）替换为 0
                    let newHexStr = "0" + hexVersion.slice(1);
                    // 转回10进制
                    let newHexNum = parseInt(newHexStr, 16);
                    // 按位还原版本号
                    let major = (newHexNum >> 24) & 0xFF;
                    let minor = (newHexNum >> 16) & 0xFF;
                    let patch = (newHexNum >> 8) & 0xFF;
                    let build = (newHexNum >> 0) & 0xFF;
                    // 拼接版本号
                    let wxVersion = `${major}.${minor}.${patch}.${build}`;
                    resolve(wxVersion); // 返回注册表值
                }
            });
        });
    })
    // hook注入微信
    ipcMain.handle('hookWx', async (event,version) => {
        const dirname = app.isPackaged ? path.dirname(app.getPath('exe')) : path.dirname(__dirname)
        const toolDir = path.join(dirname, 'tool')
        // 构建完整的 runas 命令，-Verb RunAs以管理员权限运行命令
        const runasCommand = `powershell Start-Process -FilePath '${path.join(toolDir, 'Injector.exe')}' -WindowStyle Hidden -ArgumentList '-n', 'WeChat.exe', '-i', '${path.join(toolDir, `wxhelper${version}.dll`)}' -Verb RunAs`;
        console.log(runasCommand)
        return await new Promise((resolve, reject) => {
            exec(runasCommand, (error, stdout, stderr) => {
                resolve(runasCommand)
            });
        })
    })

    // 启动微信
    ipcMain.handle('openWx', async (event) => {
        return await new Promise((resolve, reject) => {
            exec('powershell Stop-Process -Name wechat', (error, stdout, stderr) => {   // 先停止微信进程
                regKey.get('InstallPath', (err, item) => {  // 获取下载目录
                    if (err) {
                        reject(err);
                    } else {
                        const installPath = item.value
                        const WeChatExe = path.join(installPath, 'WeChat.exe')
                        const runasCommand = `powershell Start-Process -FilePath '${WeChatExe}' -Verb RunAs`;
                        exec(runasCommand, (error, stdout, stderr) => { // 启动微信进程
                            resolve(null)
                        });
                    }
                });
            });
        });
    })
}